package com.xpec.c4.db.usertype;

import org.hibernate.HibernateException;

import com.ms.db.usertype.BasicToString;
import com.xpec.c4.db.util.CodecTool;

/**
 * 把整形数组(int[])转换为String<br>
 * 使用指定的分隔符，默认为";"
 * 
 * @author Bany
 * 
 */
public class ArrayIntToString extends BasicToString {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3466708670948227717L;

	@Override
	public int[] sqlTypes() {
		return CLOB_TYPES;
	}

	@Override
	public Class<?> returnedClass() {
		return int[].class;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		/*
		 * if (x == y) return true;
		 */
		if (x != null && y != null) {
			int[] xArray = (int[]) x;
			int[] yArray = (int[]) y;
			if (xArray.length != yArray.length)
				return false;
			for (int i = 0; i < xArray.length; i++) {
				if (xArray[i] != yArray[i])
					return false;
			}
			return true;
		}
		return false;
	}

	@Override
	protected String assemble(Object obj) {
		if (obj != null) {
			int[] intArray = (int[]) obj;
			StringBuffer strBuf = new StringBuffer();
			for (int i = 0; i < intArray.length - 1; i++) {
				CodecTool.append(strBuf, String.valueOf(intArray[i]), SPLITTER);
			}
			if (intArray.length > 0) {
				strBuf.append(intArray[intArray.length - 1]);
			}
			return strBuf.toString();
		} else {
			return null;
		}
	}

	@Override
	protected int[] parse(String value) {
		if (value == null) {
			return null;
		}
		String[] strs = CodecTool.split(value, SPLITTER);
		int[] intArray = new int[strs.length];
		if (value.length() <= 0) {
			return new int[0];
		}
		for (int i = 0; i < strs.length; i++) {
			if (strs[i] != null) {
				intArray[i] = Integer.valueOf(strs[i]);
			} else {
				intArray[i] = 0;
			}
		}
		return intArray;
	}

	public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
		return ((int[]) original).clone();
	}

}
